<?php

namespace app\service;

use app\model\Account;
use app\model\UserLog;
use think\facade\Db;
use Exception;

class StatisticsService
{
    /**
     * 获取账号使用频率统计
     */
    public function getAccountUsageStats($userId, $days = 30)
    {
        $startDate = date('Y-m-d H:i:s', strtotime("-{$days} days"));

        // 获取使用频率统计
        $usageStats = UserLog::where('user_id', $userId)
            ->where('action', 'in', ['view_account', 'copy_password', 'view_decrypted_account'])
            ->where('created_at', '>=', $startDate)
            ->group('target_id')
            ->field('target_id, COUNT(*) as usage_count')
            ->select()
            ->toArray();

        $accountUsageMap = [];
        foreach ($usageStats as $stat) {
            if ($stat['target_id']) {
                $accountUsageMap[$stat['target_id']] = $stat['usage_count'];
            }
        }

        // 获取账号信息
        $accounts = Account::where('user_id', $userId)
            ->with(['category'])
            ->select();

        $result = [];
        foreach ($accounts as $account) {
            $usageCount = $accountUsageMap[$account->id] ?? 0;

            $result[] = [
                'account_id' => $account->id,
                'account_title' => $account->title,
                'category_name' => $account->category ? $account->category->name : '未分类',
                'usage_count' => $usageCount,
                'last_used_at' => $account->last_used_at,
                'created_at' => $account->created_at
            ];
        }

        // 按使用频率排序
        usort($result, function ($a, $b) {
            return $b['usage_count'] - $a['usage_count'];
        });

        return $result;
    }

    /**
     * 获取最常使用的账号
     */
    public function getMostUsedAccounts($userId, $limit = 10, $days = 30)
    {
        $stats = $this->getAccountUsageStats($userId, $days);

        return array_slice($stats, 0, $limit);
    }

    /**
     * 获取使用趋势统计
     */
    public function getUsageTrend($userId, $days = 30)
    {
        $startDate = date('Y-m-d H:i:s', strtotime("-{$days} days"));

        $trend = UserLog::where('user_id', $userId)
            ->where('action', 'in', ['view_account', 'copy_password', 'view_decrypted_account'])
            ->where('created_at', '>=', $startDate)
            ->field('DATE(created_at) as date, COUNT(*) as count')
            ->group('DATE(created_at)')
            ->order('date', 'asc')
            ->select()
            ->toArray();

        // 填充缺失的日期
        $result = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $count = 0;

            foreach ($trend as $item) {
                if ($item['date'] === $date) {
                    $count = $item['count'];
                    break;
                }
            }

            $result[] = [
                'date' => $date,
                'count' => $count
            ];
        }

        return $result;
    }

    /**
     * 获取分类使用统计
     */
    public function getCategoryUsageStats($userId, $days = 30)
    {
        $startDate = date('Y-m-d H:i:s', strtotime("-{$days} days"));

        // 获取所有账号的分类信息
        $accounts = Account::where('user_id', $userId)
            ->with(['category'])
            ->select();

        $accountCategoryMap = [];
        foreach ($accounts as $account) {
            $categoryName = $account->category ? $account->category->name : '未分类';
            $accountCategoryMap[$account->id] = $categoryName;
        }

        // 获取使用日志
        $usageLogs = UserLog::where('user_id', $userId)
            ->where('action', 'in', ['view_account', 'copy_password', 'view_decrypted_account'])
            ->where('created_at', '>=', $startDate)
            ->field('target_id')
            ->select()
            ->toArray();

        // 统计每个分类的使用次数
        $categoryStats = [];
        foreach ($usageLogs as $log) {
            $accountId = $log['target_id'];
            if (isset($accountCategoryMap[$accountId])) {
                $categoryName = $accountCategoryMap[$accountId];
                if (!isset($categoryStats[$categoryName])) {
                    $categoryStats[$categoryName] = 0;
                }
                $categoryStats[$categoryName]++;
            }
        }

        // 转换为数组格式
        $result = [];
        foreach ($categoryStats as $categoryName => $count) {
            $result[] = [
                'category_name' => $categoryName,
                'usage_count' => $count
            ];
        }

        // 按使用次数排序
        usort($result, function ($a, $b) {
            return $b['usage_count'] - $a['usage_count'];
        });

        return $result;
    }

    /**
     * 获取完整的统计数据
     */
    public function getFullStatistics($userId, $days = 30)
    {
        return [
            'account_stats' => Account::getUserAccountStats($userId),
            'most_used_accounts' => $this->getMostUsedAccounts($userId, 10, $days),
            'usage_trend' => $this->getUsageTrend($userId, $days),
            'category_usage' => $this->getCategoryUsageStats($userId, $days),
            'recent_activities' => $this->getRecentActivities($userId, 10)
        ];
    }

    /**
     * 获取最近活动
     */
    public function getRecentActivities($userId, $limit = 20)
    {
        $logs = UserLog::where('user_id', $userId)
            ->order('created_at', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();

        return $logs;
    }

    /**
     * 获取操作类型统计
     */
    public function getActionTypeStats($userId, $days = 30)
    {
        $startDate = date('Y-m-d H:i:s', strtotime("-{$days} days"));

        $stats = UserLog::where('user_id', $userId)
            ->where('created_at', '>=', $startDate)
            ->field('action, COUNT(*) as count')
            ->group('action')
            ->select()
            ->toArray();

        $actionNames = [
            'login' => '登录',
            'logout' => '退出',
            'create_account' => '创建账号',
            'update_account' => '更新账号',
            'delete_account' => '删除账号',
            'view_account' => '查看账号',
            'view_decrypted_account' => '查看解密账号',
            'copy_password' => '复制密码',
            'export_data' => '导出数据',
            'import_data' => '导入数据',
            'backup_data' => '备份数据',
            'restore_data' => '恢复数据'
        ];

        $result = [];
        foreach ($stats as $stat) {
            $result[] = [
                'action' => $stat['action'],
                'action_name' => $actionNames[$stat['action']] ?? $stat['action'],
                'count' => $stat['count']
            ];
        }

        // 按次数排序
        usort($result, function ($a, $b) {
            return $b['count'] - $a['count'];
        });

        return $result;
    }

    /**
     * 获取账号健康度评分
     */
    public function getAccountHealthScore($userId)
    {
        $accounts = Account::where('user_id', $userId)->select();

        $totalScore = 0;
        $totalAccounts = count($accounts);

        if ($totalAccounts === 0) {
            return [
                'score' => 0,
                'level' => '无数据',
                'suggestions' => []
            ];
        }

        $suggestions = [];
        $expiredCount = 0;
        $weakPasswordCount = 0; // 这里简化处理,实际需要检测密码强度
        $unusedCount = 0;

        $now = time();
        $unusedThreshold = strtotime('-90 days');

        foreach ($accounts as $account) {
            // 检查过期
            if ($account->expires_at && strtotime($account->expires_at) < $now) {
                $expiredCount++;
            }

            // 检查长时间未使用
            if (!$account->last_used_at || strtotime($account->last_used_at) < $unusedThreshold) {
                $unusedCount++;
            }
        }

        // 计算分数 (满分100)
        $score = 100;

        // 过期密码扣分
        if ($expiredCount > 0) {
            $penalty = min(30, $expiredCount * 5);
            $score -= $penalty;
            $suggestions[] = "有 {$expiredCount} 个账号密码已过期";
        }

        // 长时间未使用扣分
        if ($unusedCount > 0) {
            $penalty = min(20, $unusedCount * 2);
            $score -= $penalty;
            $suggestions[] = "有 {$unusedCount} 个账号超过90天未使用";
        }

        // 确定等级
        $level = '优秀';
        if ($score < 60) {
            $level = '需改进';
        } elseif ($score < 80) {
            $level = '良好';
        }

        return [
            'score' => max(0, $score),
            'level' => $level,
            'total_accounts' => $totalAccounts,
            'expired_count' => $expiredCount,
            'unused_count' => $unusedCount,
            'suggestions' => $suggestions
        ];
    }
}
